package com.example.noobpackage.ui.login

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.fragment.findNavController
import com.example.noobpackage.R
import com.example.noobpackage.logic.model.ApplicationUser
import com.example.noobpackage.ui.MainViewModel
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.fragment_login.account
import kotlinx.android.synthetic.main.fragment_login.password
import kotlinx.android.synthetic.main.fragment_login.register


class LoginFragment : Fragment() {

    companion object {
        const val LOGIN_SUCCESSFUL: String = "LOGIN_SUCCESSFUL"
    }

    private lateinit var savedStateHandle: SavedStateHandle
    private val loginViewModel: LoginViewModel by viewModels()
    private val sharedViewModel: MainViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        savedStateHandle = findNavController().previousBackStackEntry!!.savedStateHandle
        savedStateHandle.set(LOGIN_SUCCESSFUL, false)

        login.setOnClickListener {
            // 关闭输入法
            (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(
                0,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
            if (checkInput()) {
                val account = account.editText?.text.toString()
                val password = password.editText?.text.toString()
                login(account, password)
            }
        }

        account.editText?.doOnTextChanged { text, _, _, _ ->
            if (text != "") {
                account.error = null
            }
        }

        password.editText?.doOnTextChanged { text, _, _, _ ->
            if (text != "") {
                password.error = null
            }
        }

        register.setOnClickListener {
            val action = LoginFragmentDirections.toRegister()
            findNavController().navigate(action)
        }
    }

    private fun login(account: String, password: String) {
        // 调用viewModel的登录函数
        loginViewModel.login(account.toLong(), password).observe(viewLifecycleOwner) {
            when (it.isSuccess) {
                true -> {
                    // 登录成功
                    val applicationUser = ApplicationUser(
                        it.name,
                        it.department,
                        it.telephone,
                        account.toLong()
                    )
                    sharedViewModel.updateUserInfo(applicationUser)
                    savedStateHandle.set(LOGIN_SUCCESSFUL, true)
                    findNavController().popBackStack()
                }
                false -> {
                    Toast.makeText(context, "login failed", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun checkInput(): Boolean {
        if (account.editText?.text.toString() == "") {
            account.error = "账户不能为空"
            return false
        }

        if (password.editText?.text.toString() == "") {
            password.error = "密码不能为空"
            return false
        }

        return true
    }
}